#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (C) 1994  Ling Li
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

import os, string

def get_available_methods():
    methods = ['standard']
    try:
        import gnome.vfs
        methods.append('gnome_vfs')
    except:
        pass
    return methods

def get_filetype(filename, method=None):
    if method == None:
        method = globals()['default_method']
    if method == 'gnome_vfs':
        return GnomeVFSFileType(filename)
    else:
        return StandardFileType(filename)
    return None

def set_default(method):
    globals()['default_method'] = method
    return

class StandardFileType:

    def __init__(self, filename):
        g = globals()
        self.__filename = filename

        import mimetypes
        self.__mime_type, encoding = mimetypes.guess_type(filename)

        if not g.has_key('latest_path'):
            g['latest_path'] = ''
        dirname = os.path.dirname(filename)
        basename = os.path.basename(filename)
        if g['latest_path'] == dirname:
            self.__description = g['latest_desc'][basename]
            if self.__mime_type == None:
                self.__mime_type = g['latest_mime'][basename]
        else:
            d = []
            for name in os.listdir(dirname):
                name = os.path.join(dirname, name)
                if name.find(' ') >= 0: name = '"%s"' % name
                d.append(name)
            f = os.popen('file %s' % string.join(d))
            g['latest_desc'] = {}
            line = f.readline()
            while line != '':
                name, desc = line.split(':', 1)
                g['latest_desc'][os.path.basename(name)] = desc.strip()
                line = f.readline()
            f.close()
            self.__description = g['latest_desc'][basename]

            f = os.popen('file -i %s' % string.join(d))
            g['latest_mime'] = {}
            line = f.readline()
            while line != '':
                name, mime = line.split(':', 1)
                if mime.find(';') >= 0:
                    mime = mime.split(';')[0]
                g['latest_mime'][os.path.basename(name)] = mime.strip()
                line = f.readline()
            f.close()
            if self.__mime_type == None:
                self.__mime_type = g['latest_mime'][basename]

            g['latest_path'] = dirname

        if self.__mime_type != None:
            if not g.has_key('command_cache'): g['command_cache'] = {}
            if g['command_cache'].has_key(self.__mime_type):
                self.__command = g['command_cache'][self.__mime_type]
            else:
                import mailcap
                if not g.has_key('caps'):
                    g['caps'] = mailcap.getcaps()
                r = mailcap.findmatch(
                    g['caps'], self.__mime_type)#, filename=self.__filename)
                self.__command = r[1]
                g['command_cache'][self.__mime_type] = self.__command
        else:
            self.__command = None

        return

    def __getattr__(self, name):
        if name == 'mime_type': return self.__mime_type
        elif name == 'description': return self.__description
        elif name == 'command': return self.__command
        elif name == 'filename': return self.__filename

    def open(self):
        if self.__command == None: return 1

        args = self.__command['view'].split(' ')
        for i in range(1, len(args)):
            if args[i] == '\'%s\'':
                args[i] = self.__filename

        if not self.__command.has_key('needsterminal'):
            command = args[0]
            os.spawnlp(os.P_NOWAIT, command, *args)
        else:
            terminal = 'gnome-terminal.wrapper'
            args.insert(0, '-e')
            args.insert(0, terminal)
            os.spawnlp(os.P_NOWAIT, terminal, *args)
        return 0

class GnomeVFSFileType:

    def __init__(self, filename):
        from gnome import vfs
        self.__filename = filename
        self.__mime_type = vfs.get_mime_type(self.__filename)
        try:
            self.__desc = vfs.mime_get_description(self.__mime_type)
        except ValueError:
            self.__desc = _("Unknown type")
        self.__command = vfs.mime_get_default_application(self.__mime_type)
        return

    def __getattr__(self, name):
        if name == 'mime_type': return self.__mime_type
        elif name == 'description': return self.__desc
        elif name == 'command': return self.__command[2]
        elif name == 'filename': return self.__filename
        else: raise AttributeError, name

    def open(self):
        from gnome import vfs
        app = vfs.mime_get_default_application(self.__mime_type)
        try:
            (id, name, command, can_open_multiple_files, expects_uris,
             supported_uri_schemes, requires_terminal) = app
        except TypeError:
            return 1
        #if expects_uris:
        #    fullpath = 'file://' + self.__filename
        #else:
        #    fullpath = self.__filename
        fullpath = self.__filename
        if not requires_terminal:
            os.spawnlp(os.P_NOWAIT, command, command, fullpath)
        else:
            terminal = 'gnome-terminal.wrapper'
            os.spawnlp(os.P_NOWAIT, terminal, terminal, '-e',
                       command, fullpath)
        return 0
